<?php

class Kaskus {
  function __construct() {
    $this->appname = ", KaskusLite by judotenslab";
    $this->user_agent = "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101";
    $this->forum = "http://www.kaskus.us/";
  }

  function cURL($url, $header=NULL, $cookie=NULL, $p=NULL) {
    global $user_agent;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, $header);
    curl_setopt($ch, CURLOPT_NOBODY, $header);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    if ($p) {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
    }
    $result = curl_exec($ch);

    if ($result) {
        return $result;
    } else {
        return curl_error($ch);
    }
    curl_close($ch);
  }

  function stringBetween($start, $end, $string){
	$string = " ".$string;
	$ini = strpos($string,$start);
	if ($ini == 0) return "";
	$ini += strlen($start);
	$len = strpos($string,$end,$ini) - $ini;
	return substr($string,$ini,$len);
  }

  function get_subforum($html) {
	$awal = "a href=\"forumdisplay.php";
	$akhir = "</a>"; $tmp_a = array();
	$a = split("<a ",$html);
	foreach ($a as $itm) {
	  $t1 = $this->stringBetween("href=\"","\"",$itm);
	  if (strpos($t1,"forumdisplay.php") > -1) {
	    $subforum = array();
	    $subforum["id"] = $this->stringBetween("?f=","\"",$itm);
	    $name = $this->stringBetween("\">","###",trim(strip_tags($itm))."###");
	    if (!strpos($name,"\n")) {
		$subforum["name"] = $name;
		array_push($tmp_a,$subforum);
	    }
	  }
	}
	return $tmp_a;
  }

  function get_thread($html,&$arr=null) {
	$threads = $this->stringBetween("<!-- show threads -->","<!-- end show threads -->",$html);
	$thr = split("<tr class=\"IsForumColor",$threads);
	if ($arr) $tmp = $arr;
	else $tmp = array();

	foreach ($thr as $itm) {
		$trit = array();

		$trit["id"] = intval($this->stringBetween("td_threadtitle_","\"",$itm));
		$trit["title"] = $this->stringBetween("style=\"font-weight:bold\">","</a>",$itm);
		$trit["votes"] = intval($this->stringBetween("Thread Rating: "," votes",$itm));
		$trit["score"] = intval($this->stringBetween("votes, "," average",$itm));
		$trit["replies"] = intval(str_replace(",","",$this->stringBetween("Replies: ",", ",$itm)));
		$trit["views"] = intval(str_replace(",","",$this->stringBetween("Views: ","\"",$itm)));
		$trit["ts_id"] = intval($this->stringBetween("u=","',",$itm));
		$trit["ts_user"] = $this->stringBetween("_self')\">","</span>",$itm);

		if (strpos($itm,"alt=\"Sticky Thread\"")) $trit["sticky"] = TRUE;

		if ($trit["id"]) {
			if (!$this->is_duplicate("id",$trit["id"],$tmp)) array_push($tmp,$trit);
		}
		
	}
	return $tmp;
  }

  function crawl_thread($forum_id,$start_page=1,$count=5) {
	$threads = array();
	for ($page=$start_page;$page<($start_page + $count+1);$page++) {
	  $url = "http://www.kaskus.us/forumdisplay.php?f=$forum_id&order=desc&page=$page";
	  $html = $this->cURL($url);
	  $threads = $this->get_thread($html,$threads);
	  //array_push($threads,array("page" => $page, "threads" => $trit));
	}
	return $threads;
  }

  function proses_content($content) {
	$cts = array(); $quote = $dnone = $spoiler = false;
	foreach(split("\n",$content) as $line) {

		$tmp = trim(strip_tags($line));
		if (strpos("###".$line,"<img")) $tmp .= implode("\n",$this->break_img($line));
		if (strpos("###".$line,"<a")) {
		  $ln = implode("\n",$this->break_href($line));
		  if (count(split("<a ",$line)) > 2) $tmp .= $ln;
		  else $tmp = $ln;
		}
		if (strpos("###".$line,"<object")) {
			$vid = $this->stringBetween("value=&quot;","&amp;",$line);
			if (!$vid) $vid = $this->stringBetween("value=\"","\"",$line);
			$vid = str_replace("/v/","/watch?v=",$vid);
			$tmp = " <a href='$vid' target='_blank'>$vid</a>";
		}

		if (strpos("###".$line,"<b>Spoiler</b> for <i>")) {
		  $tit = $this->stringBetween("<b>Spoiler</b> for <i>","</i>",$line) . " :";
		  $tmp = "<small>$tit</small><br/><div class='blackquote'>";
		  $spoiler = true;
		}

		if (strpos("###".$line,"<div style=\"display: none;\">") && $spoiler) $dnone = true;
		if (strpos("###".$line,"</div>") && $spoiler && $dnone) { 
			$tmp = "</div>"; $spoiler = false; $dnone = false;
		}

		if (strpos($line,"<div class=\"smallfont\" style=\"margin-bottom:2px\">Quote:</div>")) { 
			$tmp = "<small>Quote :</small><br/><div class='blackquote'>"; $quote = true; 
		}

		if (strpos("###".$line,"</table>") && $quote) { 
			$tmp = "</div>"; $quote = false; 
		}

		array_push($cts, $tmp);
	}
	$a = str_replace("\r\n","\n",implode("\n",$cts));
	$b = str_replace("\n\n","\n",$a);
	$c = str_replace("\n\n\n","<br/>",$b);
	$d = str_replace("\n","\r\n",$c);
	$e = str_replace("\r\n","\r\n<br/>",$d);
	$f = str_replace("\r\n<br/>\r\n<br/>\r\n<br/>","\r\n<br/>",$e);
	$g = str_replace("\r\n<br/>","\r\n<br/>\r\n<br/>",$e);
	return $g;
  }

  function read_thread($tid) {
	$awal = "<!-- icon and title -->";
	$akhir = "<!-- / icon and title -->";
	$url = "http://www.kaskus.us/showthread.php?t=$tid";
	$html = $this->cURL($url);
	$tm = $this->stringBetween($awal,$akhir,$html);
	$trit["id"] = $tid;
	$trit["published"] = trim(strip_tags($this->stringBetween("<!-- status icon and date -->","<!-- / status icon and date -->",$html)));
	$trit["title"] = $this->stringBetween("<strong>","</strong>",$tm);

	$content = $this->stringBetween("<!-- message -->","<!-- / message -->",$html);
	$f = $this->proses_content($content);
	if (!$f || $f === "") $f = "The page you are looking for is temporarily unavailable.<br/>Please try again later.";
	$trit["content"] = $f;

	$trit["ts_id"] = $this->stringBetween("UserID: <b>","</b>",$html);
	$trit["ts"] = $this->stringBetween("u=".$trit["ts_id"]."\">","</a>",$html);
	$avatar = $this->stringBetween("customavatars/","\"",$html);
	if ($avatar) $trit["ts_avatar"] = "http://img.kaskus.us/customavatars/".$avatar;

	return $trit;
  }

  function read_thread_comments($tid,$startpage=1,$count=5) {
    $comments = array(); $html = $before = "";
    for ($page=$startpage;$page<($startpage+count+1);$page++) {
	$url = "http://www.kaskus.us/showthread.php?t=$tid&page=$page";
	$before = $html;
	$html = $this->cURL($url);
	if ($html === $before) { return $comments;}
	$tmp = array(); $n = 0;
	$tm = $this->stringBetween("<div id=\"posts\">","<div id=\"lastpost\">",$html);
	foreach(split("<table id=\"post",$tm) as $pst) {
		$post = array(); $n++;
		$post["id"] = $this->stringBetween("<div id=\"postmenu_","\"",$pst);
		$msg = $this->proses_content($this->stringBetween("<!-- message -->","<!-- / message -->",$pst));
		$ttl = $this->stringBetween("<strong>","</strong>",$this->stringBetween("<!-- icon and title -->","<!-- / icon and title -->",$pst));
		if ($ttl) $msg = "$ttl<br/>$msg";
		$post["message"] = $msg;
		$post["published"] = trim(strip_tags($this->stringBetween("<!-- status icon and date -->","<!-- / status icon and date -->",$pst)));

		$post["ts_id"] = $this->stringBetween("UserID: <b>","</b>",$pst);
		$post["ts"] = $this->stringBetween("u=".$post["ts_id"]."\">","</a>",$pst);
		$avatar = $this->stringBetween("customavatars/","\"",$pst);
		if ($avatar) $post["ts_avatar"] = "http://img.kaskus.us/customavatars/".$avatar;

		if ($post["id"] && $n > 2) { 
			if (!$this->is_duplicate("id",$post["id"],$comments)) array_push($comments,$post);
		}
	}
	  //array_push($comments,array("page" => $page, "comments" => $tmp));
    }
    return $comments;
  }

  function break_img($html) {
	$img = split("<img",$html);
	$tmp = array();
	foreach ($img as $itm) {
		$src = $this->stringBetween("src=\"","\"","<img ".$itm);
		if ($src && !strpos("###".$src,"images/smilies/")) {
		  if (!strpos("###".$src,"images/buttons/")) {
		    if (!strpos("###".$src,"kaskusmobile_hp.gif")) {
			if ($_REQUEST["image"]) array_push($tmp,"<img src='$src' style='max-width:400px;max-height:400px;'/>");
			else array_push($tmp," <a href='$src' target='_blank'>$src</a>");

		    }
		  }
		}
	}
	return $tmp;
  }
  function break_href($html) {
	$href = split("<a",$html);
	$tmp = array();
	foreach ($href as $itm) {
		$src = $this->stringBetween("href=\"","\" ",$itm);
		$title = $this->proses_content($this->stringBetween("\">","</a>",$itm));
		if ($src && strpos("###".$src,"http://")) {
		  if (!strpos("###".$src,"...")) {
			array_push($tmp," <a href='$src' target='_blank'>$title</a>");
		  }
		}
	}
	return $tmp;
  }

  function is_duplicate($key,$value,&$arr) {
	$ya = FALSE;
	foreach ($arr as $itm) { if ($itm[$key] === $value) $ya = TRUE; }
	return $ya;
  }

  function get_thread_by_key($key,$value,&$arr) {
	$out = array();
	foreach ($arr as $itm) { $itm = (array)$itm; if ($itm[$key] === $value) $out = $itm; }
	return $out;
  }

}

  function cetak_html($title="") {
	global $tes;
	$meta = $title . " " . $tes->appname;
	?>
	<html><head><title><? echo $title . " | KaskusLite";?></title>
	<style>
	  html,td {font-family:Georgia;font-size:16px;}
	  body { padding:0px;margin:0px;}
	  hr {	border: 2px solid #EEE;}
	  .blackquote { margin-left;30px;
			margin-right:30px;
			padding:10px;
			border:1px solid #EEE;
			background:#F8F8F8;
			font-size:14px;
			text-decoration:italic;
	  }
	  a { text-decoration: none; font-weight:bold; color: #666;}
	  .odd {background: #D3E3F5;}
	  .recommended {background: #B1CFF2;color: #FFF;}

	</style>
	<meta name="author" content="judotenslab | judotens.com"/>
	<meta name="generator" content="notepad"/>
	<meta name="keywords" content="<?=$meta;?>"/>
	<meta name="description" content="<?=$meta?>"/>
	</head><body><center><table cellspacing=0 cellpadding=0 width=100%>
	<tr><td align="left" valign="top"><br/>&nbsp;&nbsp;<b>The Lounge Kaskus</b><br/></td></tr>
	<tr><td valign="top">
	<?
  }

  function navigation($page) {
    echo "&nbsp;&nbsp;<b>Navigation : </b>";
    for ($p=1;$p<25;$p++) {
	if ($_REQUEST["thread"]) $x = "&thread=".$_REQUEST["thread"];
	if ($p != $page) echo "&nbsp;<a href='?page=$p$x'>$p</a>&nbsp;|";
	else echo "&nbsp;<font size=\"10pt\">$p</font>&nbsp;|";
    }
  }

  ini_set("max_execution_time",0);

  $tes = new Kaskus;

  $tid = $_REQUEST["thread"];

  $page = $_REQUEST["page"];
  if (!$page) $page = 1;

  if ($tid) { 
	$isi = $tes->read_thread($tid);
	cetak_html($isi["title"]);
	echo "<div style='padding:10px;'>";
	echo "<a href='http://www.kaskus.us/showthread.php?t=";
	echo $isi["id"]."' target='_blank'>".$isi["title"]."</a><br/><small>".$isi["ts"]." wrote on ".$isi["published"]."</small>";
	if (!$_REQUEST["image"]) echo " | <a href='?thread=$tid&image=true'>Turn On Image</a><hr/>";
	else  echo " | <a href='?thread=$tid'>Turn Off Image</a><hr/>";
	$content = $isi["content"];
	$content = str_replace("http://www.kaskus.us/showthread.php?t=","?thread=",$content);
	echo str_replace("\n","",str_replace("\r\n","\n",$content));
	echo "<br/>";
	if (!$_REQUEST["comments"]) echo "<hr/><a href='?thread=$tid&comments=true'>Show Comments</a>";
	else echo "<hr/><a href='?thread=$tid'>Hide Comments</a>";

	if ($_REQUEST["comments"]) {
	  echo "</td></tr>";
	  echo "<tr><td>";
	  echo "<table cellspacing=0 cellpadding=10 width=100%>";
	  $comments = $tes->read_thread_comments($tid,$page,1); $n = 0;
	  foreach ($comments as $cmt) {
		$n++; if ($n %2) $class = "odd"; else $class = "even";
		echo "<tr class='$class' style='font-size:10px;padding:2px;'><td style='width:20px;' align='center'>";
		echo $cmt["ts"] . "<br/><small>".$cmt["published"]."</small></td><td>";
		echo $cmt["message"] . "</td></tr>";
	  }
	  echo "</table><br/>";
	  navigation($page);
	}
	echo "</div>";
	exit;
  }


  //$isi = file_get_contents("kaskus.txt");
  //$threads = json_decode($isi);

  $threads = $tes->crawl_thread(21,$page,1);
  cetak_html("The Lounge Kaskus");
  navigation($page);
  echo "<br/><br/><table cellspacing=0 cellpadding=10 width=100%>";$n = 0;
  foreach ($threads as $itm) {
	$itm = (object)$itm;
	if (!$itm->sticky) {
	  $n++; if ($n %2) $class = "odd"; else $class = "even";
	  error_reporting(0);
	  $poin1 = ($itm->replies / $itm->views) * 100;
	  $poin2 = $itm->votes / $itm->score;
	  $extra = "";
	  if ($poin2 > 3) $extra = "<font color='red'>Recommended Article</font>. ";
	  if ($poin1 > 7) $extra = "<font color='#487CB8'>Interesting Article</font>. ";


	  echo "<tr class='$class'><td>";
	  echo "<a href='?thread=".$itm->id."' target='_blank'>".$itm->title."</a>";
	  echo "<br/><small>$extra"."Views : " . $itm->views . ", Replies : " . $itm->replies;
	  echo ", Votes : " . $itm->votes . ", Score : ". $itm->score;
	  echo "</small></td></tr>";
	}
  }
  echo "</table><br/>";
  navigation($page);
?></td></tr>
<tr><td align="center"><hr/>KaskusLite by judotenslab</td></tr>
</table></center></body></html>